
package nttnetworks.com.controls;

import az.encoding.html.HtmlCoding;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import nttnetworks.com.controls.questions.questionAnsw;

public class question extends javax.swing.JPanel {

    public void scr() {
        ques.setLocation(5, -scroll.getValue()*10+5);
    }
    
    public void autoSize() {
        this.ques.fixHeight();
        this.fixScroll();
    }
    
    private void fixScroll() {
        int m = (int)Math.ceil((ques.getHeight() - this.getHeight() + 10) / 10);
        if (m > 0) {
            scroll.setMaximum(m);
            int v = -ques.getY()/10;
            scroll.setValue(Math.min(v, m));
        } else {
            scroll.setMaximum(0);
        }
    }
    
    public question() {
        initComponents();
        ques.setLocation(5, 5);
        
        this.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent ce) {
                ques.setSize(question.this.getWidth()-10-scroll.getWidth(), 0);
                ques.fixHeight();

                fixScroll();
                scroll.setLocation(question.this.getWidth()-scroll.getWidth()-5, 5);
                scroll.setSize(scroll.getWidth(), question.this.getHeight()-10);
            }
        });
        
        scroll.addAdjustmentListener(new AdjustmentListener() {
            @Override
            public void adjustmentValueChanged(AdjustmentEvent ae) {
                scr();
            }
        });
        
        fixScroll();
    }
    
    private static byte[] stringToBytes(String str) {
        byte[] output = new byte[str.length()];
        for (int i=0; i<output.length; i++) {
            output[i] = (byte)((int)str.charAt(i) & 0xFF);
        }
        
        return output;
    }
    
    public void add(String question, int quetion_type, String[] answers, int numOfValidAnswers) {
//        try {
//            question = new String(stringToBytes(question), "UTF-8");
            question = HtmlCoding.decode(question);
            
            for(int i=0; i<answers.length; i++) {
//                answers[i] = new String(stringToBytes(answers[i]), "UTF-8");
                answers[i] = HtmlCoding.decode(answers[i]);
            }
            
            ques.addQuestion(question, answers, quetion_type, numOfValidAnswers);
            fixScroll();
//        } catch (UnsupportedEncodingException ex) {
//            Logger.getLogger(question.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }

    public void add(int type, String question_json) {
        try {
            ScriptEngineManager script = new ScriptEngineManager();
            ScriptEngine js = script.getEngineByExtension("js");
            
            js.eval("var json="+question_json+";");
            String question = (String)js.eval("json.question");        
            
            if (type == 1) {    //selection
                int num = (int)((double)js.eval("json.num"));
                String[] answers = new String[(int)(double)js.eval("json.answers.length")];
                for (int i=0; i<answers.length; i++) {
                    answers[i] = (String)js.eval("json.answers["+i+"]");
                }
                
                add(question, type, answers, num);
            } else {    //textbox
                add(question, type, new String[] {}, 1);
            }
        } catch (ScriptException ex) { }
    }
    
    /**
     * @return Số lượng câu hỏi trong danh sách
     */
    public int length() {
        return ques.length();
    }
    
    /**
     * Lấy một question trong danh sách câu hỏi
     * @param index: question thứ bao nhiêu trong danh sách
     * @return 
     */
    public questionAnsw get(int index) {
        return ques.get(index);
    }
    
    /**
     * Xóa tất cả danh sách các câu hỏi.
     */
    public void clear() {
        ques.clear();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scroll = new javax.swing.JScrollBar();
        ques = new nttnetworks.com.controls.questions.questionPage();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 153, 153), 1, true));
        addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                formMouseWheelMoved(evt);
            }
        });
        setLayout(null);
        add(scroll);
        scroll.setBounds(360, 70, 17, 48);

        javax.swing.GroupLayout quesLayout = new javax.swing.GroupLayout(ques);
        ques.setLayout(quesLayout);
        quesLayout.setHorizontalGroup(
            quesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        quesLayout.setVerticalGroup(
            quesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        add(ques);
        ques.setBounds(30, 50, 100, 100);
    }// </editor-fold>//GEN-END:initComponents

    private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_formMouseWheelMoved
        scroll.setValue(scroll.getValue() + 
                (int)evt.getPreciseWheelRotation() * evt.getScrollAmount());
    }//GEN-LAST:event_formMouseWheelMoved

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private nttnetworks.com.controls.questions.questionPage ques;
    private javax.swing.JScrollBar scroll;
    // End of variables declaration//GEN-END:variables
}
